#/usr/bin/env python3
# -*- coding: utf-8 -*-

import itertools

# Method 1, some error
def pi(N):
    """
    计算PI值
    """
    natural = itertools.count(1)
    ns = itertools.takewhile(lambda x: x <= N, natural)
    lst = [x for x in ns if x % 2 != 0] 
    res = 0
    for i, v in enumerate(lst):
        if i % 2 != 0:
            v = 0 -v
        res = res + 4/v
    return res

# Method 2

def Npi(N):
    """
    计算pi值
    """
    natural = itertools.count(1, 2)
    ns = itertools.takewhile(lambda x: x <= 2 * N -1, natural)

    # map函数添加正负号
    res = sum(
            map(lambda x: 4/x if x % 4 == 1 else -4/x, ns)
            )


    # 枚举方法添加正负号
    #res = 0
    #for i, v in enumerate(ns):
    #    if i % 2:
    #        v = -v
    #    res += 4/v
    return res

# test
print(Npi(10))
print(Npi(100))
print(Npi(1000))
print(Npi(10000))
assert 3.04 < Npi(10) < 3.05
assert 3.13 < Npi(100) < 3.14
assert 3.141 < Npi(1000) < 3.141, 'Npi = %f' % Npi(1000)
assert 3.1414 < Npi(10000) < 3.1415
